import React, { useState } from 'react';
import { connect } from 'dva';
import { useUpdateEffect } from '@umijs/hooks';
import { Tooltip, Row, Col, Card, Form, Input, Button, Modal, message, Divider} from 'antd';
import dynamic from 'umi/dynamic';
import LoadingComponent from '@/components/PageLoading/index';
import SlickTable from '@/components/SlickTable';
import useSlickTableTemp from '@/hooks/useSlickTableTemp';
import moment from 'moment';
import request from '@/utils/request';
import styles from './styles.less';

const namespace = 'busiComponent';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

// 判断空对象
const isEmptyObject = obj => {
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const BusiComponentAdd = dynamic({
  loader: () => import('./components/BusiComponentAdd'),
  loading: LoadingComponent,
});

const SelectBusiObj = dynamic({
  loader: () => import('./components/common/SelectBusiObj'),
  loading: LoadingComponent,
});

function BusiComponent(props) {
  const { getFieldDecorator } = props.form;
  const [params, setParams] = useState({}); // 查询条件
  const [selectBusiObjVisibleFlag, setSelectBusiobjVisibleFlag] = useState(false); // 选择业务对象弹窗展示/隐藏标记

  // 初始化表格数据
  const { tableProps } = useSlickTableTemp(
    { pageSize: 10 },
    'pmc/pcms/busiComponent/queryPage',
    params
  );

  useUpdateEffect(() => {
    if (isEmptyObject(props.selectBusiComponent)) {
      setParams({
        ...params,
      });
    }
  }, [props.selectBusiComponent]);

  // 通过dva存当前需要传递的数据
  const saveSelectBusiComponent = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectBusiComponent`,
      payload: params,
    });
  };

  const saveBusiComponentAddVisibleFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveBusiComponentAddVisibleFlag`,
      payload: params,
    });
  };

  const saveBusiComponentAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveBusiComponentAddType`,
      payload: params,
    });
  };

  // 查询
  const handleQuery = () => {
    const formData = props.form.getFieldsValue();
    formData.pageNum = 1;
    formData.pageSize = 10;
    formData.gb_reset = true;
    setParams(formData);
  };

  // 重置查询条件
  const handleReset = () => {
    props.form.resetFields();
  };

  // 新增对象组件
  const handleAdd = () => {
    saveBusiComponentAddType('add');
    saveBusiComponentAddVisibleFlag(true);
  };

  // 修改对象组件
  const handleModify = record => {
    saveSelectBusiComponent(record);
    saveBusiComponentAddType('modify');
    saveBusiComponentAddVisibleFlag(true);
  };

  // 删除对象组件
  const handleDelete = record => {
    Modal.confirm({
      content: '确定删除选中对象组件？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request('pmc/pcms/busiComponent/delete', {
          method: 'GET',
          data: { busiCompId: record.busiCompId },
        }).then(res => {
          if (res && res.success === true) {
            message.success('删除成功');
            saveSelectBusiComponent({});
          } else if (res && res.errMessage) {
            message.error(res.errMessage);
          } else {
            message.error('删除失败');
          }
        });
      },
    });
  }

  // const busiComponentAddCallBack = () => {

  // };

  // 选择业务对象
  const handleSelectBusiObj = () => {
    setSelectBusiobjVisibleFlag(true);
  };

  // 选择业务对象回调函数
  const selectBusiObjCallBacks = {
    selectBusiObjCallBack: data => {
      props.form.setFieldsValue({
        busiObjName: data.busiObjName,
      });
    },
    handleVisibleFlag: flag => {
      setSelectBusiobjVisibleFlag(flag);
    },
  };

  const cellStyle = {
    maxWidth: 200,
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis',
    cursor: 'pointer',
  };

  const columns = [
    {
      title: '对象组件名称',
      dataIndex: 'busiCompName',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '对象组件编码',
      dataIndex: 'busiCompCode',
    },
    {
      title: '对象类型',
      dataIndex: 'objTypeName',
    },
    {
      title: '对象名称',
      dataIndex: 'busiObjName',
    },
    {
      title: '对象编码',
      dataIndex: 'busiObjNbr',
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null),
    },
    {
      title: '修改时间',
      dataIndex: 'updateDate',
      render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null),
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <span>
            <a
              onClick={() => {
                handleModify(record);
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                handleDelete(record);
              }}
            >
              删除
            </a>
          </span>
        );
      },
    },
  ];

  return (
    <div>
      <Card
        title="对象组件管理"
        className="cute"
        style={{ height: '100%' }}
        extra={
          <div>
            <Button
              className="margin-left"
              type="primary"
              onClick={() => {
                handleAdd();
              }}
            >
              新增对象组件
            </Button>
          </div>
        }
      >
        <Form style={{ marginBottom: 10 }}>
          <Row>
            <Col span={6}>
              <Form.Item label="对象组件名称" {...formItemLayout}>
                {getFieldDecorator('busiCompName')(<Input />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="对象组件编码" {...formItemLayout}>
                {getFieldDecorator('busiCompCode')(<Input />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="业务对象" {...formItemLayout}>
                {getFieldDecorator('busiObjName')(
                  <Input.Search
                    readOnly
                    placeholder="请选择业务对象"
                    onSearch={handleSelectBusiObj}
                    allowClear
                  />
                )}
              </Form.Item>
            </Col>
          </Row>
          <div style={{ textAlign: 'center' }}>
            <Button type="primary" className="margin-right" onClick={handleQuery}>
              查询
            </Button>
            <Button type="default" onClick={handleReset}>
              重置
            </Button>
          </div>
        </Form>
        <SlickTable
          rowKey={record => record.busiCompId}
          columns={columns}
          {...tableProps}
          rowClassName={record => {
            return record.busiCompId === props.selectBusiComponent.busiCompId
              ? styles.clickRowStyle
              : '';
          }}
          onRow={record => {
            return {
              onClick: () => {
                saveSelectBusiComponent(record);
              },
            };
          }}
        />
      </Card>
      {/* 选择业务对象 */}
      {selectBusiObjVisibleFlag ? (
        <SelectBusiObj modalVisible={selectBusiObjVisibleFlag} {...selectBusiObjCallBacks} />
      ) : null}
      {/* 新增/修改业务对象 */}
      {props.busiComponentAddVisibleFlag ? (
        <BusiComponentAdd modalVisible={props.busiComponentAddVisibleFlag} />
      ) : null}
    </div>
  );
}

export default connect(({ busiComponent, setting }) => ({
  selectBusiComponent: busiComponent.selectBusiComponent,
  busiComponentAddVisibleFlag: busiComponent.busiComponentAddVisibleFlag,
  busiComponentAddType: busiComponent.busiComponentAddType,
  size: setting.size,
}))(Form.create()(BusiComponent));
